#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;

int main(int argc, char** argv) {
    if (argc < 2) {
        cout << "\nError: You had too few parameters.\n" << endl;
        return -1;
    }

    cv::VideoCapture cap;
    if (!cap.open(argv[1])) {
        cout << "Could not open " << argv[1] << endl;
        return 1;
    }

    double rate = cap.get(CV_CAP_PROP_FPS);
    cv::Mat frame, gray, canny;
    int delay = 1000 / rate;
    cout << "rate = " << rate << ", delay = " << delay << endl;
    cout << "\nEsc to exit, or let it run out, then any key  to release capture and exit.\n" << endl;
    int frame_count = 0;
    while(1){
        cap >> frame;
        if(!frame.data) {
            cout << "Done with capture" << endl;
            break;
        }

        cv::imshow("Raw Video", frame);

        cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY);
        cv::imshow("Gray video", gray);

        cv::Canny(gray, canny, 100, 255);
        cv::imshow("Canny Video", canny);

        // a
        cv::Mat all(frame.rows,3 * frame.cols, CV_8UC3, cv::Scalar::all(0));
        cv::cvtColor(gray, gray, cv::COLOR_GRAY2BGR);
        cv::cvtColor(canny, canny, cv::COLOR_GRAY2BGR);
        
        cv::Mat sub = all.colRange(0, frame.cols);
        frame.copyTo(sub);
        sub = all.colRange(frame.cols, 2 * frame.cols);
        gray.copyTo(sub);
        sub = all.colRange(2*frame.cols, 3*frame.cols);
        canny.copyTo(sub);
        // b
        cv::Scalar color = CV_RGB(255, 0, 0);
        cv::putText(all, "raw video", cv::Point(50, 30), CV_FONT_HERSHEY_DUPLEX, 1.0f, color);
        cv::putText(all, "gray video", cv::Point(50 + frame.cols, 30), CV_FONT_HERSHEY_DUPLEX, 1.0f, color);
        cv::putText(all, "canny video", cv::Point(50 + frame.cols*2, 30), CV_FONT_HERSHEY_DUPLEX, 1.0f, color);
        cv::imshow("All Video", all);

        if ((cv::waitKey(delay) & 255) == 27) 
            break;
    }
    cv::waitKey();
    cap.release();

    return 0;
}